package com.osard.test_record;

import android.os.Handler;
import android.os.Looper;
import android.view.View;

import androidx.annotation.IdRes;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 按照设定间隔允许再次点击，避免点击过快触发多次。
 * <p>
 * 针对同一触发者View生效
 */
public class ClickLookUtils {

    //线程安全Map
    private final static Map<Integer, ClickLookUtils> MAP = new ConcurrentHashMap<>();

    @IdRes
    private final int viewId;
    private int interval;

    private ClickLookUtils(int viewId) {
        this.viewId = viewId;
        this.interval = 200;
    }

    /**
     * 创建工厂
     *
     * @param view 点击的View
     */
    public static ClickLookUtils createFactory(View view) {
        return createFactory(view.getId());
    }

    /**
     * 创建工厂
     *
     * @param viewId 点击View的ID
     */
    public static ClickLookUtils createFactory(@IdRes int viewId) {
        ClickLookUtils obj = MAP.get(viewId);
        if (null == obj) {
            obj = new ClickLookUtils(viewId);
        }
        return obj;
    }

    /**
     * 设置间隔，单位毫秒
     * <p>
     * 默认200毫秒
     */
    public ClickLookUtils setInterval(int interval) {
        this.interval = interval;
        return this;
    }

    /**
     * 检查是否可以再次触发点击
     *
     * @return true: 不允许触发点击，false: 可以触发点击
     */
    public boolean checkLook() {
        ClickLookUtils obj = MAP.get(viewId);
        //缓存内检测到对应view时禁止再次点击
        if (null == obj) {

            MAP.put(viewId, this);
            //添加计时任务，时间到后清除缓存，此时允许点击
            new Handler(Looper.myLooper()).postDelayed(() -> MAP.remove(viewId), interval);

            return false;
        }
        return true;
    }
}
